package com.cssl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cssl.domain.DtsAd;
import com.cssl.domain.DtsRole;
import com.cssl.domain.dto.DtsRoleDto;
import com.cssl.mapper.DtsRoleMapper;
import com.cssl.service.DtsRoleService;
import com.cssl.util.RedisUtil;
import com.cssl.util.ObjectMapperUtil;
import com.cssl.util.StorageVariable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class DtsRoleServiceImpl implements DtsRoleService {
    @Autowired
    private DtsRoleMapper roleMapper;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ObjectMapper objectMapper;

    private ObjectMapperUtil objectMapperUtil;

    @Override
    public List<DtsRole> getRoleById(List<Integer> ids, Integer aid) {
        //先从redis中获取
        String s = template.opsForValue().get(StorageVariable.AMIN_ROLE + ":" + aid);
        if (StrUtil.isEmpty(s)) {
            //从数据库查询
            List<DtsRole> roleById = roleMapper.getRoleById(ids);
            try {
                template.opsForValue().set(StorageVariable.AMIN_ROLE + ":" + aid, objectMapper.writeValueAsString(roleById));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            template.opsForValue().set(StorageVariable.AMIN_ROLE + ":" + aid, objectMapperUtil.toJsonString(roleById));
            return roleById;
        }

        //存在
        List<DtsRole> dtsRoles = objectMapperUtil.fromJsonString(s, new TypeReference<List<DtsRole>>() {
        });
        return dtsRoles;
    }

    //查询所有角色
    @Override
    public List<DtsRole> queryAll() {
        List<DtsRole> dtsRoles;
        if (redisUtil.hasKey("RoleList")) {
            System.out.println("从 Redis 中获取数据");
            dtsRoles = (List<DtsRole>) redisUtil.get("RoleList");
        } else {

            dtsRoles = roleMapper.queryAll();
            redisUtil.set("RoleList", roleMapper.queryAll(), 3600);
        }
        return dtsRoles;
    }

    @Override
    public Map getDtsRoleList(DtsRoleDto dto) {
        // Redis Key 存储，包含页码和条件
        StringBuilder redisKeyBuilder = new StringBuilder("RoleList");

        if (dto.getRolename() != null && !dto.getRolename().isEmpty()) {
            redisKeyBuilder.append(":Rolename:").append(dto.getRolename());
        }

        redisKeyBuilder.append(":page:").append(dto.getPageNum());
        String redisKey = redisKeyBuilder.toString();
        List<DtsRole> roleList = null;
        // 检查 Redis 中是否存在当前页的数据
        if (redisUtil.hasKey(redisKey)) {

            roleList = (List<DtsRole>) redisUtil.get(redisKey);
            Map<String, Object> map1 = new HashMap<>();
            // 获取存储的总数

            map1.put("list", roleList);
            map1.put("total", redisUtil.get("RoleList:total")); // 使用从 Redis 获取的总数
            map1.put("pageNum", dto.getPageNum());
            map1.put("pageSize", dto.getPageSize());
            return map1;
        } else {
            // 开始分页
            Page page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize());

            roleList = roleMapper.getDtsRoleList(dto);
            Map<String, Object> map = new HashMap<>();
            // 计算总数
//            long total = page.getTotal();

            // 将查询结果放入 Redis，设置过期时间，例如：1小时
            redisUtil.set(redisKey, roleList, 3600);
            redisUtil.set("RoleList:total", roleMapper.getDtsRoleCount(), 3600);

            map.put("list", page.getResult());
            map.put("total", page.getTotal()); // 使用从数据库计算的总数
            map.put("totalPage", page.getPages());
            map.put("pageNum", page.getPageNum());
            map.put("pageSize", page.getPageSize());
            return map;
        }
    }

    @Override
    public int RoleNameCount(String name) {
        return roleMapper.RoleNameCount(name);
    }

    @Override
    public int createRole(DtsRole role) {
        // 首先检查是否有任何以 "DtsAdList:" 开头的键
        Set<String> keys = redisUtil.keys("RoleList:*");
        if (!keys.isEmpty()) {
            // 删除所有匹配的键
            for (String key : keys) {
                redisUtil.del(key);
            }
        }
        return roleMapper.createRole(role);
    }

    @Override
    public int updateRole(DtsRole role) {
        // 首先检查是否有任何以 "DtsAdList:" 开头的键
        Set<String> keys = redisUtil.keys("RoleList:*");
        if (!keys.isEmpty()) {
            // 删除所有匹配的键
            for (String key : keys) {
                redisUtil.del(key);
            }
        }
        return roleMapper.updateRole(role);
    }

    @Override
    public int deleteRole(DtsRole role) {
        // 首先检查是否有任何以 "DtsAdList:" 开头的键
        Set<String> keys = redisUtil.keys("RoleList:*");
        if (!keys.isEmpty()) {
            // 删除所有匹配的键
            for (String key : keys) {
                redisUtil.del(key);
            }
        }
        return roleMapper.deleteRole(role);
    }


}
